#!/bin/sh
### BEGIN INIT INFO
# Provides:          sidekiq
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Manage sidekiq worker
# Description:       Start, stop, restart sidekiq worker.
### END INIT INFO

APP_DIR="<%= current_path %>"
LOG_FILE="$APP_DIR/log/sidekiq.log"
PID_FILE="$APP_DIR/tmp/pids/sidekiq.pid"
SIDEKIQ="sidekiq"
SIDEKIQCTL="sidekiqctl"
APP_ENV="<%= fetch(:rails_env) %>"
BUNDLE="bundle"
AS_USER=<%= fetch(:mb_sidekiq_user, user) %>
CONCURRENCY=<%= fetch(:mb_sidekiq_concurrency) %>

START_CMD="cd $APP_DIR; $BUNDLE exec $SIDEKIQ -d -e $APP_ENV -P $PID_FILE --concurrency $CONCURRENCY -L $LOG_FILE"
CTL_CMD="cd $APP_DIR; $BUNDLE exec $SIDEKIQCTL"
RETVAL=0


run () {
  if [ "$(id -un)" = "$AS_USER" ]; then
    eval $1
  else
    su -c "$1" - $AS_USER
  fi
}

start() {

  status
  if [ $? -eq 1 ]; then

    [ -d $APP_DIR ] || (echo "$APP_DIR not found!.. Exiting"; exit 6)
    echo "Starting $SIDEKIQ message processor .. "
    run "$START_CMD"
    RETVAL=$?
    #Sleeping for 8 seconds for process to be precisely visible in process table - See status ()
    sleep 8
    return $RETVAL
  else
    echo "$SIDEKIQ message processor is already running .. "
  fi


}

stop() {

    status
    if [ $? -eq 0 ]; then

      echo "Stopping $SIDEKIQ message processor .."
      run "$CTL_CMD stop $PID_FILE"
      RETVAL=$?
      return $RETVAL

    else
      echo "$SIDEKIQ message processor is already stopped .. "
    fi

}

status() {

  ps -ef | egrep 'sidekiq [0-9]+.[0-9]+.[0-9]+' | grep -v grep
  return $?
}


case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status

        if [ $? -eq 0 ]; then
             echo "$SIDEKIQ message processor is running .."
             RETVAL=0
         else
             echo "$SIDEKIQ message processor is stopped .."
             RETVAL=1
         fi
        ;;
    *)
        echo "Usage: $0 {start|stop|status}"
        exit 0
        ;;
esac
exit $RETVAL
